'use strict';

const Controller = require('egg').Controller;
const crypto = require('crypto')
class UserController extends Controller {
  //注册
  async reg() {
    const { ctx } = this
    let { username, password, repassword } = ctx.request.body
    ctx.validate({
      username: {
        required: true, type: 'string', desc: '用户名', range: {
          min: 5,
          max: 20
        },
      },
      password: { required: true, type: 'string', desc: '密码' },
      repassword: { required: true, type: 'string', desc: '确认密码' },
    }, 
    // {
    //   equals: [
    //     ['password', 'repassword']
    //   ]
    // }
    )
    if(password!==repassword){
      return ctx.apiFail('两次输入密码不一致')
    }
    //用户名是否存在
    if (await ctx.model.User.findOne({
      where: {
        username
      }
    })) {
      ctx.throw(400, '该用户已存在')
    }
    //创建用户
    let user = await ctx.model.User.create({
      username,
      password,
    })
    if (!user) {
      ctx.throw(400, '注册失败')
    }
    user = JSON.parse(JSON.stringify(user))
    user.token = ctx.getToken(user)
    //加入缓存
    if (!await this.service.cache.set('user_' + user.id, user.token)) {
      ctx.throw(400, '登录失败')
    }
    delete user.password
    ctx.apiSuccess(user);
  }

  //校验密码
  checkPassword(password, hash_password) {
    const hamc = crypto.createHash('sha256', this.config.crypto.secret)
    hamc.update(password)
    if (hamc.digest('hex') !== hash_password) {
      this.ctx.throw(400, '密码错误')
    }
    return true
  }

  async login() {
    const { ctx } = this;
    let { username, password } = ctx.request.body;
    ctx.validate({
      username: { required: true, type: 'string', desc: '用户名' },
      password: { required: true, type: 'string', desc: '密码' }
    })
    let user = await ctx.model.User.findOne({
      where: {
        username
      }
    })
    if (!user) {
      return ctx.apiFail('当前用户不存在')
    }
    //验证密码
    this.checkPassword(password, user.password)
    user = JSON.parse(JSON.stringify(user))
    //生成token
    user.token = ctx.getToken(user)
    delete user.password
    //加入缓存
    if (!await this.service.cache.set('user_' + user.id, user.token)) {
      ctx.throw(400, '登录失败')
    }
    ctx.apiSuccess(user)

  }

  async logout() {
    const { ctx, service } = this
    const currentUserId = ctx.authUser.id;
    if (!await service.cache.remove('user_' + currentUserId)) {
      ctx.throw(400, '退出登录失败')
    }
    ctx.apiSuccess('退出登录成功')

  }

  //修改用户信息
  async update(){
    let {ctx}=this
    let {id}=ctx.authUser
    let params=ctx.request.body
    let user=await ctx.model.User.findOne({
      where:{
        id
      }
    })
    let res=await user.update(params);
    delete res.password;
    ctx.apiSuccess(res)
  }
  //关注或取消
  async follow() {
    const { ctx } = this
    const user_id = ctx.authUser.id
    ctx.validate({ follow_id: { type: 'int', required: true, desc: '关注用户id' } })
    const { follow_id } = ctx.request.body
    if (!(await this.service.user.exist(follow_id))) {
      return ctx.apiFail('此用户不存在')
    }
    if (user_id === follow_id) {
      return ctx.apiFail('不能关注自己')
    }

    const follow = await ctx.model.Follow.findOne({
      where: {
        user_id,
        follow_id
      }
    })
    if (follow) {
      follow.destroy()
      return ctx.apiSuccess({ status: false, msg: '取消关注成功' })
    } else {
      await ctx.model.Follow.create({
        user_id,
        follow_id,
      })
      ctx.apiSuccess({ status: true, msg: '关注成功' })
    }
  }
  //我的关注列表
  async follows() {
    let { ctx } = this
    let user_id = ctx.query.user_id
    ctx.validate({user_id:{required:true,type:'int',desc:'用户id'}})
    let res = await ctx.page('Follow', {
      user_id
    }, {
      include: [{
        model: ctx.model.User,
        as: 'user_follow',
        attributes: ['id', 'username', 'nickname', 'avatar']
      }],
      order: [['created_time', 'DESC']]
    })
    res = res.map(i => {
      return {
        id: i.user_follow.id,
        name: i.user_follow.nickname || i.user_follow.username,
        avatar: i.user_follow.avatar
      }
    })
    ctx.apiSuccess(res)
  }

  //我的粉丝列表
  async fens() {
    let { ctx } = this
    let user_id = ctx.query.user_id
    ctx.validate({user_id:{required:true,type:'int',desc:'用户id'}})
    let res = await ctx.page('Follow',
      {
        follow_id: user_id
      }, {
      include: [{
        model: ctx.model.User,
        as: 'user_fen',
        attributes: ['id', 'username', 'nickname', 'avatar']
      }],
      order: [['created_time', 'DESC']]
    })
    res = res.map(i => {
      return {
        id: i.user_fen.id,
        name: i.user_fen.nickname || i.user_fen.username,
        avatar: i.user_fen.avatar
      }
    })
    ctx.apiSuccess(res)
  }

  //统计相关数据
  async user_info() {
    let { ctx, service } = this
    let id=null
    if(ctx.header.token){
      id = this.app.jwt.verify(ctx.header.token, this.app.config.jwt.secret).id
    }
    // let id = ctx.authUser.id
    ctx.validate({ user_id: { type: 'int', desc: '用户id' } })
    let user_id = ctx.query.user_id ? ctx.query.user_id : id
    let res = await service.user.getUserInfo(user_id)
    if (!res) {
      return ctx.apiFail('该用户不存在')
    }
    let fenCount = 0;
    let followCount = 0;
    let favaCount = 0
    let videoCount=0
    // let follow=false
    followCount = await service.user.getFollowCount(user_id)
    fenCount = await service.user.getFenCount(user_id)
    favaCount = await service.user.getFavaCount(user_id)
    videoCount=await service.user.getVideoCount(user_id)
    if (id !== user_id) {
       let isFollow = await service.user.isFollow(id, user_id)
       return ctx.apiSuccess({
        user: res,
        fenCount,
        followCount,
        favaCount,
        videoCount,
        isFollow
      })
    }
    ctx.apiSuccess({
      user: res,
      fenCount,
      followCount,
      favaCount,
      videoCount,
    })
  }


}

module.exports = UserController;
